package yd.launcher;

import javax.swing.*;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class TextUndoManager {
    private Map<JTextComponent, UndoManager> undoManagerMap = new HashMap<>(2);

    public void put(JTextComponent textComponent){
        UndoManager undoManager = new UndoManager();
        undoManager.setLimit(50);
        undoManagerMap.put(textComponent, undoManager);

        textComponent.getDocument().addUndoableEditListener(new UndoableEditListener() {
            @Override
            public void undoableEditHappened(UndoableEditEvent e) {
                undoManager.addEdit(e.getEdit());//每次编辑操作都会触发这个事件；而e.getEdit()记录了这个编辑操作；这里将这个编辑操作存入undoManager进行管理
            }
        });
        textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Z"),"undo");
        textComponent.getActionMap().put("undo", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
            }
        });
        textComponent.getInputMap().put(KeyStroke.getKeyStroke("control Y"),"redo");
        textComponent.getActionMap().put("redo", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (undoManager.canRedo()) {
                    undoManager.redo();
                }
            }
        });
    }
}
